package algorithm1udp_v3;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.FileWriter;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Task1 implements Callable<Object> {

	static Logger logger = LoggerFactory.getLogger(Task1.class);

	private static void writeLeader() {
		SystemInfo info = SystemInfo.INSTANCE;
		BufferedWriter fileLeader;
		try {
			fileLeader = new BufferedWriter(new FileWriter("leader"));
			fileLeader.write(info.leader.toString());
			fileLeader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void sendMessages() {
		SystemInfo info = SystemInfo.INSTANCE;
		try {
			if (info.leader.toString().equals(
					InetAddress.getLocalHost().getHostName())) {
				// prozesu izenak hartu timeoutetik nere burua ezbaitako bertako keyetan
				for (String name : info.timeout.keySet()) {
					try {
						InetAddress host = InetAddress.getByName(name); 
						DatagramSocket socket = new DatagramSocket();
				        ByteArrayOutputStream baos = new ByteArrayOutputStream();
				        ObjectOutputStream oos = new ObjectOutputStream(baos);
						Message message = new Message(new StringBuilder(
								InetAddress.getLocalHost().getHostName()),
								info.recovered);
				        oos.writeObject(message);
				        oos.close();
				        byte[] data= baos.toByteArray();
				        DatagramPacket packet = new DatagramPacket(data, data.length, host, 12345);
				        socket.send(packet);
						logger.info("mezua bidalita: " + message.toString() + " "+name+"-ari");
						socket.close();
					} catch (Exception e) {
						logger.info("ERROREA: Task1 mezua bidaltzean: " + name
								+ "-ari");
						e.printStackTrace();
					}
				}
			} else {
				// logger.info("TASK1: ez zara liderra ezinda bidali");
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}

	}

	@Override
	public Object call() throws Exception {
		// logger.info("1. Ataza Martxan");
		// Thread.sleep(info.incarnation[0]+info.timeUnit[0]); //Delay hau
		// Iniciationen sartu da scheduler exekutatzerakoan
		writeLeader();
		ScheduledExecutorService executor = Executors
				.newSingleThreadScheduledExecutor();
		SystemInfo info = SystemInfo.INSTANCE;
		executor.scheduleAtFixedRate(new Runnable() {
			public void run() {
				sendMessages();
			}
		}, 0, info.timeUnit[0], TimeUnit.MILLISECONDS);
		return null;
	}

}
